function multi_voi_avg
% multi_voi_avg  - generate Multi-VOI averaging plots
%
% FORMAT:       multi_voi_avg
%
% Note: all input will be handled by uiget* methods

% Bettina's script for automatic Multi-VOI AVG plot generation
%
% Version:  v0.7c
% Build:    7120607
% Date:     Dec-06 2007, 7:53 AM CET
% Author:   Jochen Weber, Brain Innovation, B.V., Maastricht, NL
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% choose a start folder
startfolder = uigetdir(pwd, 'Please choose your start folder...');
if isequal(startfolder, 0)
    error('Cancel pressed.');
end
cd(startfolder);

% set empty objects to make sure
vtcl = false;
voil = false;

% big try / catch
try

    % VTC selection
    [vtc, vtcl] = BVQXfile('*.vtc');
    if isempty(vtc)
        error('No VTC selected.');
    end

    % VOI selection
    [voi, voil] = BVQXfile('*.voi');
    if isempty(voi)
        if vtcl
            vtc.ClearObject;
        end
        error('No VOI selected.');
    end

    % creating VOI color array
    vcol = zeros(voi.NrOfVOIs, 3);
    for cc=1:voi.NrOfVOIs
        vcol(cc,:) = voi.VOI(cc).Color;
    end

    % VOI file name (without extension)
    [voifile{1:2}] = fileparts(voi.FilenameOnDisk);

    % VOI time course data
    voitc = vtc.VOITimeCourse(voi);

    % selection of AVG files (second parameter is Inf for multiple files)
    %
    % Note: for selection, first choose last file, then press shift and
    %       select first file, to keep good "order"
    avgs = BVQXfile('*.avg', Inf);

    % adding data?
    adata = questdlg('Do you wish to add data to the plots?', ...
        'User request', 'Yes', 'No', 'No');
    if strcmpi(adata, 'yes')
        adata = true;
    else
        adata = false;
    end

    % Figure, Snapshot options
    figopts.figsize  = [800, 600]; % width, height
    figopts.snapshot = '';         % dynamic filename
    figopts.snpclose = true;       % close after snapshot is taken
    figopts.title  = '';
    figopts.xlabel = 'Volumes (time in TRs)';
    figopts.ylabel = '%-BSC (fMRI Response)';

    % iterate over AVGs
    for ac = 1:numel(avgs)

        % get a reference
        avg = avgs(ac);

        % get filename (without extension)
        [avgfile{1:2}] = fileparts(avg.FilenameOnDisk);

        % plot data
        [plotdata, splotdata] = avg.Average(0, voitc);
        if ~any(splotdata(:))
            splotdata = [];
        end

        % generate plot
        %
        % 1st argument: plotdata
        % 2nd argument: se plotdata
        % 3rd argument: [] (axes object)
        % 4th argument: colors (VOI)
        % 5th argument: figure, snapshot options
        figopts.snapshot = [voifile{2} '_' avgfile{2} '.png'];
        figopts.title = strrep([voifile{2} ' ' avgfile{2}], '_', '-');
        avg.Plot(plotdata, splotdata, [], vcol, figopts);

        % with added data?
        if adata

            % select DAT file
            adat = BVQXfile('*.dat');
            if isempty(adat)
                adata = false;
                continue;
            end

            % generate second figopts
            figopt2 = figopts;
            figopt2.adddata = adat.Curve(1).PlotData(:,1);
            figopt2.addedcol = [255, 255, 255];
            figopt2.snapshot = strrep(figopts.snapshot, '.png', '_added.png');
            avg.Plot(plotdata, [], [], vcol, figopt2);
        end
    end

    % clear objects
    if vtcl
        vtc.ClearObject;
    end
    if voil
        voi.ClearObject;
    end
    
% big catch
catch
    if vtcl
        vtc.ClearObject;
    end
    if voil
        voi.ClearObject;
    end
    rethrow(lasterror);
end
